<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Controller for the shifts
 *
 * @category RedCross
 * @package Admin_Controller
 */
class Admin_ShiftController extends Zend_Controller_Action
{
  private $_roleService;
  private $_shiftService;
  private $_shiftroleService;
  private $_shiftExchangeService;

  public function init()
  {
    $this->_roleService     = RedCross_Factory::getService('Core_Service_Role');
    $this->_shiftService     = RedCross_Factory::getService('Core_Service_Shift');
    $this->_shiftroleService  = RedCross_Factory::getService('Core_Service_ShiftRole');
    $this->_shiftExchangeService = RedCross_Factory::getService('Core_Service_ShiftExchange');

    $ajaxContext = $this->_helper->getHelper('AjaxContext');
    $ajaxContext->addActionContext('memberroletable', 'json')
            ->addActionContext('memberroletable', 'html')
                ->addActionContext('addshiftrole', 'html')
        ->addActionContext('deleteshiftrole','json')
        ->addActionContext('setisleader', 'json')
        ->addActionContext('edit', 'json')
        ->addActionContext('removememberfromrole', 'json')
                ->addActionContext('deleteshiftrole', 'json')
        ->initContext();
  }

  public function indexAction()
  {
        $filterContent = array(
            'active'        =>  'Gjeldende',
            'inactive'      =>  'Utgåtte',
            'all'           =>  'Alle',
            'unconfirmed'   =>  'Kun vakter med ubekreftede roller',
            'future_without_filled_roles' => 'Fremtidige vakter som har ikke fylte roller',
            'past_whithout_shift_report' => 'Utgåtte vakter som mangler vaktrapport',
            'submited_but_not_confirmed_shift_report' => 'Vakter som har ubekreftet vaktrapport'
        );
        $filterForm = $this->view->filterForm = $this->view->filterForm($filterContent);
        $filterForm->setAction($this->view->url(array('module' => 'admin', 'controller' => 'shift'), null, true));

        $service = $this->_shiftService;

        $request = $this->getRequest();
        if ($request->isGet() && $this->_getParam('filter', false) && $filterForm->isValid($request->getQuery())) {
            $value = $filterForm->getValue('filter');
            switch ($value) {
                case 'active':
                    $this->view->shifts = $service->fetchAllActive(false);
                    break;
                case 'inactive':
                    $this->view->shifts = $service->fetchAllInActive(false);
                    break;
                case 'all':
                    $this->view->shifts = $service->fetchAll(false);
                    break;
                case 'unconfirmed':
                    $this->view->shifts = $service->fetchAllContainingUnconfirmedShiftNotifications(false);
                    break;
                case 'future_without_filled_roles':
                    $this->view->shifts = $service->fetchAllFutureWithoutFilledRoles(false);
                    break;
                case 'past_whithout_shift_report':
                    $this->view->shifts = $service->fetchAllPastWithoutShiftReport(false);
                    break;
                case 'submited_but_not_confirmed_shift_report':
                    $this->view->shifts = $service->fetchAllWithUnconfirmedShiftReport(false);
            }
        }

        if (!isset($this->view->shifts)) {
            $this->view->shifts = $service->fetchAllActive(false);
        }
  }

  private function generate_notify_pdf($shift)
  {
    $pdf = new RedCross_Pdf_ShiftNotification();
    $pdf->generate($shift);
    return $pdf->Output('ignored', 'S');
  }

  private function get_primary_mail($member)
  {
  }

  private function send_notification_mail($shift, $shift_roles, $text)
  {
    $mail = new RedCross_Mail_Base();

    $mail->addPdf('utkalling.pdf', $this->generate_notify_pdf($shift));
    	
    $from_date = new RedCross_Date($shift->from_date, RedCross_Date::DB_FMT);
    $appearance_date = new RedCross_Date($shift->appearance_time, RedCross_Date::DB_FMT);
    $mail->setSubject('[Vaktutkalling] ' . $shift->name . " (" . $appearance_date->getDateTimeStr() . ")");

    $content = new Zend_View();
    $content->setScriptPath(APPLICATION_PATH . '/layouts/main/emails/');

    $success = 0;
    $failed = 0;
    foreach ($shift_roles as $shift_role)
    {
      if (!is_null($shift_role->member_id))
      {
        $mail->clearRecipients();
        $date = new RedCross_Date();
        $key = sha1($date->export() . ':' . $shift_role->id .
          ':' . $shift_role->member_id);
        $content->assign('key', $key);
        $name = $shift_role->Member->first_name . ' ' . $shift_role->Member->last_name;
        $content->assign('name', $name);
        $content->assign('first_name', $shift_role->Member->first_name);
        $content->assign('last-name', $shift_role->Member->last_name);
        $content->assign('id', $shift_role->id);
        $content->assign('text', $text);
        
        $from_date = new RedCross_Date($shift->from_date, RedCross_Date::DB_FMT);
        $to_date = new RedCross_Date($shift->to_date, RedCross_Date::DB_FMT);
        
        $content->assign('shiftname', $shift->name);
        $content->assign('shiftdate', $from_date->getDateStr());
        $content->assign('shiftplace', $shift->Event->location);
        $content->assign('showuptime', $appearance_date->getTimeStr());
        $content->assign('fromtime', $from_date->getTimeStr());
        $content->assign('totime', $to_date->getTimeStr());
        
        foreach ($shift_role->Member->emails as $addr)
        {
        	if($addr->is_main) {
				$mail->addTo($addr->address, $name);
			}
        }
        $body = $content->render('shift-notification.phtml');
        try
        {
          $mail->setBodyText($body);
          $mail->send();

          $shift_role->notification_sent_time = $date->export();
          $shift_role->notification_confirmed_time = null;
          $shift_role->save();
          ++$success;
        }
        catch (Exception $e)
        {
          ++$failed;
          $this->view->flashMessage()->addMessage('Feilet å sende mail til ' .
            $addr->address . ' (' . $e->getMessage() .
            ')', RedCross_View_Helper_FlashMessage::ERROR);
        }
      }
    }
    $this->view->flashMessage()->addMessage('Utkalling sendt til ' .
      $success . ' medlem' . ($success > 1 ? 'er' : '') .
      ($failed !==0 ? ', ' . $failed . ' feilet' :
      ''), $failed !== 0 ?
      RedCross_View_Helper_FlashMessage::ERROR :
      RedCross_View_Helper_FlashMessage::SUCCESS);
  }

  public function notifyAllAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'notify');

    $id = $this->_getParam('id');

    $validator = new Zend_Validate_Int();
    if (!$validator->isValid($id)) {
      throw new RedCross_Exception_ValidationFailed();
    }
        $shift = $this->_shiftService->fetch((int) $id);
    $this->view->shift = $shift;
        $form = new Admin_Form_Shift_Notifyall();
        $text = null;
        $request = $this->getRequest();
        if($request->isPost() && $form->isValid($request->getPost())){
            $text = $form->getValue('text');
            $this->send_notification_mail($shift, $shift->Roles, $text);
      return $this->_helper->redirector('view', 'shift', 'core', array('id' => $shift->id));
        }

    $this->view->form = $form;
  }

  public function notifyAction()
  {
    $this->_helper->acl()->isAllowed('service:shift', 'notify');

    $id = $this->_getParam('id');

    $validator = new Zend_Validate_Int();
    if (!$validator->isValid($id)) {
      throw new RedCross_Exception_ValidationFailed();
    }

    $shift_role = $this->_shiftroleService->fetch((int) $id);
    $shift = $shift_role->Shift;
        $this->view->shift = $shift;
        $form = new Admin_Form_Shift_Notifyall();
        $text = null;
        $request = $this->getRequest();
        if($request->isPost() && $form->isValid($request->getPost())){
            $text = $form->getValue('text');
            $this->send_notification_mail($shift, array($shift_role), $text);
            return $this->_helper->redirector('view', 'shift', 'core', array('id' => $shift->id));
        }
        $memberNameAndRole = $this->_shiftroleService->fetchMemberNameAndRoleName((int) $id);
        $memberName = $memberNameAndRole[0]['Member']['first_name'] . ' ' . $memberNameAndRole[0]['Member']['last_name'];
        $this->view->memberName = $memberName;
        $roleName = $memberNameAndRole[0]['Role']['name'];
        $this->view->roleName = $roleName;
        $this->view->form = $form;

  }

    public function editAction()
    {
        $this->_helper->acl()->isAllowed('service:shift', 'edit');
        $editForm = new Admin_Form_Shift_Edit();

        $request = $this->getRequest();
        if($request->isPost() && $request->isXmlHttpRequest()) {
            $response = $editForm->processAjax($request->getPost());

            if ($response === 'true') {
                $values = $request->getParams();
                $validator = new Zend_Validate_Int();
                if (!$validator->isValid($values['shift_id'])) {
                    throw new RedCross_Exception_ValidationFailed();
                }
                $shiftId = (int) $values['shift_id'];

                $shift = $this->_shiftService->fetch($shiftId);
                if(!$shift) {
                    throw new RedCross_Exception_NotFound();
                }

                $values['id'] = $shiftId;
                unset($values['shift_id']);

                $temp = $values['appearance_date'] . ' ' . $values['appearance_time'];
                $appearance_date = new RedCross_Date($temp, RedCross_Date::NO_DATETIME_FMT);
                $values['appearance_time'] = $appearance_date->export();

                $temp = $values['from_date'] . ' ' . $values['from_time'];
                $from_date = new RedCross_Date($temp, RedCross_Date::NO_DATETIME_FMT);
                $values['from_date'] = $from_date->export();

                $temp = $values['to_date'] . ' ' . $values['to_time'];
                $to_date = new RedCross_Date($temp, RedCross_Date::NO_DATETIME_FMT);
                $values['to_date'] = $to_date->export();

                $shift->fromArray($values);
                if($this->_shiftService->save($shift)) {
                    $response = Zend_Json::decode($response);
                    $this->view->status = $response;
                    return;
                } else {
                    //should not get here
                    $this->view->status = 'Could not save the shift';
                    return;
                }
            } else {
                //errors
                $response = Zend_Json::decode($response);
                $this->view->status = $response;
            }
        } else {
            $shiftId = $this->_getParam('id', false);

            $validator = new Zend_Validate_Int();
            if (!$validator->isValid($shiftId)) {
              throw new RedCross_Exception_ValidationFailed();
            }
            $shiftId = (int) $shiftId;

            $shift = $this->_shiftService->fetchByIdForEditShift($shiftId);
            if (!$shift) {
                throw new RedCross_Exception_NotFound();
            }
            $this->view->shift = $shift;
            $this->view->event = $shift->Event;

            $hidden_id = new Zend_Form_Element_Hidden('shift_id');
            $hidden_id->clearDecorators();
            $hidden_id->addDecorators(array('ViewHelper', array('HtmlTag', array('tag' => 'li'))));
            $hidden_id->setValue($shiftId);
            $editForm->addElement($hidden_id);

            $this->_populateEditForm($shift, $editForm);

            $this->view->form = $editForm;

            $this->view->roles = $shift->Roles;

            $allRoles = $this->_roleService->fetchAllSorted();
            $this->view->allroles = $allRoles;

            $shiftExchanges = $this->_shiftExchangeService->fetchAllUnhandledForShift($shift->id);
            $this->view->shiftExchanges = $shiftExchanges;
        }
    }

    private function _populateEditForm(Core_Model_Shift $shift, Admin_Form_Shift_Edit $editForm)
    {
        $formValues = array();
        $formValues['name'] = $shift['name'];

        $date = new RedCross_Date();

        $date->import($shift['appearance_time']);
        $formValues['appearance_date'] = $date->getDateStr();
        $formValues['appearance_time'] = $date->getTimeStr();

        $date->import($shift['from_date']);
        $formValues['from_date'] = $date->getDateStr();
        $formValues['from_time'] = $date->getTimeStr();

        $date->import($shift['to_date']);
        $formValues['to_date'] = $date->getDateStr();
        $formValues['to_time'] = $date->getTimeStr();

        $formValues['special_description'] = $shift['special_description'];
        $formValues['equipment_list'] = $shift['equipment_list'];
        $editForm->populate($formValues);
    }

  public function createAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'create');

    $event_id = $this->_getParam('event', false);

    $validator = new Zend_Validate_Int();
    if (!$validator->isValid($event_id)) {
      throw new RedCross_Exception_ValidationFailed();
    }
    $event_id = (int) $event_id;

    $eventService = $this->_helper->getService('Core_Service_Event');
    $event = $eventService->fetch($event_id);
    if (!$event) {
      throw new RedCross_Exception_ValidationFailed();
    }

        $eventName = $event->name;
    $event_from_date = new RedCross_Date();
    $event_from_date->import($event->from_date);

    $event_to_date = new RedCross_Date();
    $event_to_date->import($event->to_date);

    $form = new Admin_Form_Shift_Create();
        $nameElement = $form->getElement('name');
        $nameElement->setValue($eventName);

    $request = $this->getRequest();
    if ($request->isPost() && $form->isValid($request->getPost())){
      $values = $form->getValues();

      $from_date = new RedCross_Date($values['from_date'] . ' ' . $values['from_time'] . ':00', RedCross_Date::NO_DATETIME_FMT);
      $to_date = new RedCross_Date($values['to_date'] . ' ' . $values['to_time'] . ':00', RedCross_Date::NO_DATETIME_FMT);


      $time_error = false;
      if ($from_date->getTimestamp() < $event_from_date->getTimestamp()) {
        $tmp = 'Vaktens starttid er før arrangementets starttid!';
        $form->getElement('from_time')->addError($tmp);
        $time_error = true;
      }
      if ($to_date->getTimestamp() > $event_to_date->getTimestamp()) {
        $tmp = 'Vaktens sluttid er etter arrangementets sluttid!';
        $form->getElement('to_time')->addError($tmp);
        $time_error = true;
      }
      if ($time_error === true) {
        $this->view->form = $form;
        return;
      }

      $values['from_date'] = $from_date->export();
      $values['to_date'] = $to_date->export();

      $shift = $this->_shiftService->create($event_id, $values);
      if(!$shift) {
        throw new RedCross_Exception('Could not create a shift');
      }
      $shift_id = $shift->id;
      $roles = $this->_roleService->fetchByTemplateId((int) $form->getValue('shift_template'));

      $valuesForShiftRoleModel = array();
      foreach ($roles as $role) {
        $number = $role['ShiftTemplateRole']['0']['number'];
        if((int)$number > 1){
          for($i = 1; $i <= $number; $i++) {
            $valuesForShiftRoleModel[] = $role['id'];
          }
        } else {
          $valuesForShiftRoleModel[] = $role['id'];
        }
      }

      // Create a Transaction
      $manager = Doctrine_Manager::getInstance();
      $conn = $manager->getCurrentConnection();
      $conn->beginTransaction();

      foreach ($valuesForShiftRoleModel as $role) {
        $shiftRole = new Core_Model_ShiftRole();
        $shiftRole->role_id = $role;
        $shiftRole->leader = false;
        $shiftRole->shift_id = $shift_id;

        $this->_shiftroleService->createShiftRole($shiftRole);
      }

      try {
        $conn->commit();
      } catch (Doctrine_Exception $e) {
        $conn->rollback();
      }

      return $this->_helper->redirector('edit', 'shift', 'admin', array('id' => $shift_id));
    }
    else
    {
      $shifts = array();
      foreach ($event->Shifts as $shift)
        $shifts[] = $shift;
      usort($shifts, array('RedCross_Global', 'shift_sort_cmp'));
      $form->getElement('from_date')->setValue($event_from_date->getDateStr());
      $form->getElement('from_time')->setValue($event_from_date->getTimeStr());
      $form->getElement('to_date')->setValue($event_to_date->getDateStr());
      $form->getElement('to_time')->setValue($event_to_date->getTimeStr());
      Core_Service_Event::check_shift_coverage($this->view, $event, $shifts);
      $this->view->form = $form;
    }
  }

  public function replaceRoleAction()
  {
        $shiftId = $this->_getParam('shift');
        $roleId = $this->_getParam('role');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($shiftId) || !$validator->isValid($roleId)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $shiftId = (int) $shiftId;
        $roleId = (int) $roleId;

        $shift = $this->_shiftService->fetchByIdIncludingMembers($shiftId);

        // Deny access if not allowed by the ACL
        // Checks if the member is a shift leader has access otherwise (has access to ShiftRole->replaceRole)
        $this->_helper->acl()->isAllowed($shift, 'replaceRole');

        // Fetch member to replace
        // Ensure that he is a member of the shift
        $role = $this->hasRole($shift, $roleId);
        if (is_null($role)) {
          // The member does not belong to the shift
          $this->view->error = true;
            return;
        }

        // Sjekke om den innloggede brukeren er shift leader, og om rollen som skal endres er en leder
        if (!$this->view->acl()->isAllowed('service:shiftRole', 'replaceRole', false) && $role->leader) {
            throw new RedCross_Exception_Unauthorized('A shift leader does not have permission to replace a shift leader');
        }

        $this->view->role = $role;

        // Fetch available users
        $form = new Admin_Form_Shift_FillRoles($role, false, array($role['id'] => $role['Member']['id']));
        $this->view->form = $form;

        // Do the changing
        $request = $this->getRequest();
        if ($request->isPost() && $form->isValid($request->getPost())) {
            $shiftRoleService = $this->_helper->getService('Core_Service_ShiftRole');

          try {
            $shiftRoleService->replaceRole($role, $form->getValue('role' . $role['id']));
          } catch (RedCross_Exception_Unauthorized $e) {
              // User was not allowed to access the function (not an admin)
              // Check if user is the shift leader, by checking the IsShiftLeader-assertion
                if ($this->view->acl()->isAllowed($shift, 'replaceRole')) {
                    // Call the function again, disabling the exception-throwing (since the user is the shift leader)
                    $shiftRoleService->disableAclException();
                    $shiftRoleService->replaceRole($role, $form->getValue('role' . $role['id']));
                } else {
                    throw $e;
                }
          }
            $this->_helper->redirector('view', null, null, array('id' => $shiftId));
        }
  }

  private function hasRole($shift, $roleId)
  {
        foreach ($shift->Roles as $role) {
          if ($role->id == $roleId) {
            return $role;
          }
        }
        return null;
  }

  public function memberroletableAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'edit');

    $request = $this->getRequest();
    if($request->isXmlHttpRequest()) {
      $ajaxParams = $request->getParams();

      $memberService = $this->_helper->getService('Core_Service_Member');

      if($ajaxParams['format'] == 'json') {
        $memberId = (int)$ajaxParams['member_id'];
        $shiftRoleId = (int)$ajaxParams['role'];

        if($memberId != null && $shiftRoleId != null) {
          $shiftRole = $this->_shiftroleService->fetch((int)$shiftRoleId);
          $shiftRole->member_id = $memberId;
          $shiftRole->notification_sent_time = null;
          $shiftRole->notification_confirmed_time = null;

          if($this->_shiftroleService->save($shiftRole)) {
            $member = $memberService->fetch((int)$shiftRole->member_id);
            $this->view->first_name = $member->first_name;
            $this->view->last_name = $member->last_name;
            $this->view->sr_id = $shiftRole->id;
          } else {
            throw new Exception('Something went wrong');
          }
        } else {
          throw new Exception('Something went wrong');
        }
      } else {
        $shift_role_id = $ajaxParams['role'];

        $ignore_courses = $this->_getParam('ignore_courses', false) != false;
        $ignore_passive = $this->_getParam('ignore_passive', false) != false;
        $ignore_permanent_passive = $this->_getParam('ignore_permanent_passive', false) != false;

        $options = array(
          Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_PASSIVE => $ignore_passive,
          Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_PERMANENT_PASSIVE => $ignore_permanent_passive,
          Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_COURSES => $ignore_courses
        );

        $this->view->ignore_passive = $ignore_passive;
        $this->view->ignore_permanent_passive = $ignore_permanent_passive;
        $this->view->ignore_courses = $ignore_courses;

        $shiftRole = $this->_shiftroleService->fetch((int)$shift_role_id);
        $membersArray = $memberService->fetchEligibleForRole($shiftRole, $options);

        $this->view->members = $membersArray;
        $this->view->shift_role_id = $shift_role_id;
      }
    }
  }

  public function deleteshiftroleAction() {
        $this->_helper->acl()->isAllowed('service:shift', 'edit');

        $shiftRoleId = $this->_getParam('role', false);

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($shiftRoleId)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $shiftRoleId = (int) $shiftRoleId;

        $shiftRole = $this->_shiftroleService->fetch($shiftRoleId);
        if (!$shiftRole) {
            throw new RedCross_Exception_NotFound();
        }
        $shiftId = $shiftRole->shift_id;

        $isAjax = $this->getRequest()->isXmlHttpRequest();
        if ($isAjax) {
            $result = $this->_shiftroleService->delete($shiftRole);
            if ($result) {
                $this->view->shift = $shiftId;
                $this->view->role = $shiftRoleId;
                return;
            } else {
                throw new Exception('Something went wrong');
            }
        }

        $confirmForm = new Admin_Form_Shift_ConfirmDeleteShiftRole();
        $this->view->confirmForm = $confirmForm;

        $request = $this->getRequest();
        if(!$request->isPost() || !$confirmForm->isValid($request->getPost())) {
            return;
        }

        $result = $this->_shiftroleService->delete($shiftRole);
        if ($result) {
            $this->view->flashMessage()->addMessage('Fjernet en rolle fra vakten', RedCross_View_Helper_FlashMessage::SUCCESS);
            $this->_helper->redirector('edit', null, null, array('id' => $shiftId));
        } else {
            $this->view->flashMessage()->addMessage('Klarte ikke å fjerne rollen', RedCross_View_Helper_FlashMessage::ERROR);
            $this->_helper->redirector('edit', null, null, array('id' => $shiftId));
        }
  }

  public function addshiftroleAction()
    {
        $this->_helper->acl()->isAllowed('service:shift', 'edit');

    $request = $this->getRequest();
    if($request->isXmlHttpRequest()) {
      $ajaxParams = $request->getParams();
      $roleId = $ajaxParams['role'];
      $shiftId = $ajaxParams['shift'];

            $validator = new Zend_Validate_Int();
        if (!$validator->isValid($roleId) || !$validator->isValid($shiftId)) {
          throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
        }

      if($roleId != null && $shiftId != null) {
        $shiftRole = new Core_Model_ShiftRole;
        $shiftRole->shift_id = (int)$shiftId;
        $shiftRole->role_id = (int)$roleId;
                $shiftRole->leader = false;

        if($this->_shiftroleService->save($shiftRole)) {
          $role = $this->_roleService->fetch((int)$roleId);
          $this->view->role = $role->name;
          $this->view->role_id = $shiftRole->role_id;
          $this->view->sr_id = (int)$shiftRole->id;
          $this->view->shift_id = $shiftRole->shift_id;
                    return;
        }
      }
            throw new Exception('Something went wrong');
    }
  }

  public function reportAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'approveReport');

    $shift_id = $this->_getParam('id', false);

    $validator = new Zend_Validate_Int();
    if (!$validator->isValid($shift_id)) {
      throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
    }
    $shift_id = (int)$shift_id;

    $shift = $this->_shiftService->fetchByIdJoinOnShiftReportShiftRolesRolesAndMember($shift_id);
    if (!is_object($shift)) {
      throw new RedCross_Exception_NotFound('Objekt med angitt id ikke funnet');
    }
        $this->view->shift = $shift;

    if (is_null($shift->ShiftReport)) {
      throw new RedCross_Exception_NotFound('Angitt rapport ikke funnet');
    }

        $approveReportForm = new Admin_Form_Shift_ApproveReport();

    $editReportForm = new Core_Form_Shift_Report();
    $editReportForm->fillForm($shift);

    $message = null;

    $request = $this->getRequest();
    if ($request->isPost())
    {
      $values = $request->getPost();
      if (isset($values['approve_report']) && $approveReportForm->isValid($values))
      {
                $result = $this->_shiftService->approveShiftReport($shift);
                $message =
                    $result ?
                    $this->view->flashMessage()->renderMessage('Rapport godkjent', RedCross_View_Helper_FlashMessage::SUCCESS) :
                    $this->view->flashMessage()->renderMessage('En ukjent feil oppstod', RedCross_View_Helper_FlashMessage::ERROR);
      } else if ($editReportForm->isValid($values)) {
                $result = $this->_shiftService->submitShiftReport($editReportForm->getValues(), $shift);
                $message =
                    $result ?
                    $this->view->flashMessage()->renderMessage('Rapport endret', RedCross_View_Helper_FlashMessage::SUCCESS) :
                    $this->view->flashMessage()->renderMessage('En ukjent feil oppstod', RedCross_View_Helper_FlashMessage::ERROR);
      }
    }

    $this->view->message = $message;
    $this->view->approveReportForm = $approveReportForm;
    $this->view->editReportForm = $editReportForm;
    $this->view->shift = $shift;
    $this->view->shiftReport = $shift->ShiftReport;
  }

  public function reportpdfAction()
  {
    $shiftId = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
    if (!$validator->isValid($shiftId)) {
      throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
    }

    $shift = $this->_shiftService->fetch((int)$shiftId);

    if (is_null($shift->shift_report_id)) {
      throw new RedCross_Exception_NotFound('Angitt vakt har ingen vaktrapport');
    }

        $report = new RedCross_Pdf_ShiftReport();
        $report->generate($shift->ShiftReport);

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $this->getResponse()->setHeader('Content-type', 'application/pdf', true);
        $this->getResponse()->setHeader('Content-disposition', 'attachment; filename=vaktrapport-' . $shift->id . '.pdf', true);
        $this->getResponse()->setBody($report->Output('ignored', 'S'));
  }

  public function setisleaderAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'edit');

    $request = $this->getRequest();
    if($request->isXmlHttpRequest()) {
      $ajaxParams = $this->getRequest()->getParams();

      if($ajaxParams['format'] == 'json') {
        $shiftRoleId = $ajaxParams['role'];
        $shiftRole = $this->_shiftroleService->fetch((int) $shiftRoleId);

        $isLeader = $shiftRole->leader;
        if($isLeader) {
          $shiftRole->leader = false;
        } else {
          $shiftRole->leader = true;
        }

        if($this->_shiftroleService->save($shiftRole)) {
          $this->view->isLeader = $shiftRole->leader;
        } else {
          throw new Exception('Something went wrong');
        }
      }
    }
  }

  public function removememberfromroleAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'edit');

    $request = $this->getRequest();
        $values = $request->getParams();

        $shiftRoleId = $values['role'];

        $validator = new Zend_Validate_Int();
    if (!$validator->isValid($shiftRoleId)) {
      throw new RedCross_Exception_ValidationFailed();
        }
        $shiftRoleId = (int)$shiftRoleId;

        $shiftRole = $this->_shiftroleService->fetch($shiftRoleId);
        $shiftRole->member_id = null;

        $result = $this->_shiftroleService->save($shiftRole);
        $isAjax = $request->isXmlHttpRequest();
        if($result && $isAjax) {
            $this->view->sr_id = $shiftRoleId;
        } else if(!$result && $isAjax) {
            throw new Exception('Something went wrong');
        } else if($result && !$isAjax) {
            $this->view->flashMessage()->addMessage('Fjernet brukeren fra rollen', RedCross_View_Helper_FlashMessage::SUCCESS);
            $this->_helper->redirector('edit', null, null, array('id' => $shiftRole->Shift->id));
        } else {
            $this->view->flashMessage()->addMessage('Kunne ikke utføre oppdateringen', RedCross_View_Helper_FlashMessage::ERROR);
            $this->_helper->redirector('edit', null, null, array('id' => $shiftRole->Shift->id));
        }
  }

  public function deleteAction()
  {
        $this->_helper->acl()->isAllowed('service:shift', 'delete');

    $shiftId = $this->_getParam('id');

    $validator = new Zend_Validate_Int();
    if (!$validator->isValid($shiftId)) {
      throw new RedCross_Exception_ValidationFailed();
        }
    $shiftId = (int) $shiftId;

    $shift = $this->_shiftService->fetch($shiftId);
    if (is_null($shift)) {
      throw new RedCross_Exception_NotFound();
    }

    $form = new Admin_Form_Shift_Delete();

    $request = $this->getRequest();
    if ($request->isPost() && $form->isValid($request->getPost())) {
      $this->_shiftService->delete($shiftId);
      $this->view->flashMessage()->addMessage('Slettet vakten', RedCross_View_Helper_FlashMessage::SUCCESS);
      $this->_helper->redirector('index');
    }

    $this->view->shift = $shift;
    $this->view->form = $form;
  }
}
